//
//  MCAppVersionManager.m
//  CloudSteward
//
//  Created by coderxslee on 2020/12/11.
//  Copyright © 2020 CoderXSLee. All rights reserved.
//

#import "MCAppVersionManager.h"
#import <MCKit/MCAlert.h>

#define AppStoreUrl_Chine @"https://itunes.apple.com/cn/lookup"
#define AppStoreUrl_Other @"https://itunes.apple.com/lookup"

typedef void(^CacheBlockData)(NSError *error, NSDictionary *dic);

@interface MCAppVersionManager ()

/// App_Store_ID
@property (nonatomic, strong) NSString *appID;

/// App的信息
@property (nonatomic, strong) MCAppInfoModel *appInfo;

@end



@implementation MCAppVersionManager

- (void)setAppID:(NSString *)appID {
    if (_appID != appID) {
        _appID = appID;
    }
}

/// 显示App 版本号
- (void)showAppVerSion {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSInteger tag = [version stringByReplacingOccurrencesOfString:@"." withString:@""].integerValue;
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    UIView *view = [window viewWithTag:tag];
    
    if (!view && ![view isKindOfClass:[UILabel class]]) {
        // CGFloat x = [CSUICommon isNotchScreen]?APP_SCREEN_WIDTH*0.09:30;
        CGFloat x = UIScreen.mainScreen.bounds.size.width * ([MCAppVersionManager isNotchScreen] ? .81 : .63);
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, 5, 28, 10)];
        label.font = [UIFont boldSystemFontOfSize:10];
        label.textAlignment = NSTextAlignmentCenter;
        // label.cornerRadius = 2;
        // label.backgroundColor = UIColor.greenColor;
        label.text = version;
        [window addSubview:label];
    }else {
        [window bringSubviewToFront:view];
    }
}

//版本检查更新
- (void)versionUpdate {
    __block NSDictionary *chinaDict;//加cn链接的返回数据
    [self requesAppInfoOfAppStoreWithURL:AppStoreUrl_Chine resultBlock:^(NSError *error, NSDictionary *dic) {
        if (error) { return; }
        chinaDict = dic;
        [self requesAppInfoOfAppStoreWithURL:AppStoreUrl_Other resultBlock:^(NSError *error, NSDictionary *dic) {
            if (error) { return; }
            NSDictionary *newDic = [self analyzeCompareLatestWithChinaData:chinaDict otherData:dic];
            NSArray *arr = newDic[@"results"];
            MCAppInfoModel *info = [MCAppInfoModel appInfoWithDict:arr.firstObject];
            MCAppVersionManager.sharedInstance.appInfo = info;
            NSString *appStoreVersion = info.version;
            NSString *currentVersion = [self appVersion];
            if ([self isNeedUpdate:appStoreVersion curVersion:currentVersion]) {
                NSString *msg = [NSString stringWithFormat:@"%@", info.releaseNotes];
                MCAlert *alert = [[MCAlert alloc] initWithTitle:@"发现新版本" message:msg delegate:nil cancelButtonTitle:@"以后再说" otherButtonTitles:@"立即更新", nil];
                alert.lineSpacing = 2;
                alert.paragraphSpacing = 4;
                alert.font = [UIFont systemFontOfSize:15];
                alert.contentAlignment = NSTextAlignmentLeft;
                [alert setClickBlock:^(MCAlert *alertView, NSInteger buttonIndex) {
                    if (buttonIndex == 1) {
                        // 跳转搜索页面，还是用 trackName 比较靠谱，但是返回的数据有可能为空的情况使用本地 DisplayName
                        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                        NSString *displayName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
                        NSString *name = info.trackName ? info.trackName : displayName;
                        NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
                        name = [name stringByAddingPercentEncodingWithAllowedCharacters:set];
                        NSString *baseUrl = @"https://itunes.apple.com/WebObjects/MZStore.woa/wa/search";
                        NSString *str = [NSString stringWithFormat:@"%@?mt=8&submit=edit&term=%@#software", baseUrl, name];
                        NSURL *url = [NSURL URLWithString:str];
                        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                    }
                }];
                [alert show];
            }
        }];
    }];
}

- (BOOL)isNeedUpdate:(NSString *)appStoreVersion curVersion:(NSString *)currentVersion {
    NSArray *currentVersionArray = [currentVersion componentsSeparatedByString:@"."];
    NSArray *appStoreVersionArray = [appStoreVersion componentsSeparatedByString:@"."];
    BOOL needUpdate = NO;
    //比较版本号大小
    int minv = (int)MIN(currentVersionArray.count, appStoreVersionArray.count);
    int maxv = (int)MAX(currentVersionArray.count, appStoreVersionArray.count);
    
    BOOL isCompareBig = (currentVersionArray.count != appStoreVersionArray.count) ? YES : NO;
    
    int cver = 0;
    int aver = 0;
    
    // 如果版本号位数不一致，则忽略多余的不进行比较。
    int count = isCompareBig ? minv : maxv;
    
    for (int i = 0; i < count; i++) {
        int aValue = [NSString stringWithFormat:@"%@",appStoreVersionArray[i]].intValue;
        aver = (appStoreVersionArray.count > i) ? aValue : 0;
        
        int cValue = [NSString stringWithFormat:@"%@",currentVersionArray[i]].intValue;
        cver = (currentVersionArray.count > i) ? cValue : 0;
        
        if(aver != cver) {
            return (aver > cver)? YES : NO;
        }
    }
    
    return needUpdate;
}

/// 去AppStore请求App信息
- (void)requesAppInfoOfAppStoreWithURL:(NSString *)url resultBlock:(CacheBlockData)result {
    NSAssert(_appID.length, @"appID不能为空，请在 [[MCAppVersionManager sharedInstance] setAppID:@\"appID\"] 中设置AppID");
    // 一定要是POST请求，要不返回的信息不准确
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [[NSString stringWithFormat:@"id=%@",self.appID] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                result(error, nil);
            }else {
                NSDictionary *dic =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                result(nil, dic);
            }
        });
    }];
    [task resume];
}
 
- (NSString *)appVersion {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}
 
// 分析比较最新的数据 中国地区/其他地区
- (NSDictionary *)analyzeCompareLatestWithChinaData:(NSDictionary *)chinaDict otherData:(NSDictionary *)otherDict {
    MCAppInfoModel *china = [MCAppInfoModel appInfoWithDict:chinaDict];
    MCAppInfoModel *other = [MCAppInfoModel appInfoWithDict:otherDict];
    
    NSDate *chinaDate;
    NSDate *otherDate;
    
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    if ([china.currentVersionReleaseDate rangeOfString:@"T"].location != NSNotFound) {
        NSArray *array = [china.currentVersionReleaseDate componentsSeparatedByString:@"T"];
        NSString *chinaDateString = [array firstObject];
        // chinaDate =  [DataTimeTool dateFromString:new_currentVersionReleaseDate_cn DateFormat:@"y-M-d"];
        chinaDate = [dateFormat dateFromString:chinaDateString];
    }
    
    if ([other.currentVersionReleaseDate rangeOfString:@"T"].location != NSNotFound) {
        NSArray  *array = [other.currentVersionReleaseDate componentsSeparatedByString:@"T"];
        NSString *otherDateString = [array firstObject];
        // otherDate =  [DataTimeTool dateFromString:new_currentVersionReleaseDate DateFormat:@"y-M-d"];
        otherDate = [dateFormat dateFromString:otherDateString];
    }
    
    NSComparisonResult result = [chinaDate compare:otherDate];
    if (result == NSOrderedDescending) {
        return chinaDict;
    }else if (result == NSOrderedAscending){
        return otherDict;
    }
    return otherDict;
}
 
- (BOOL)isReview:(NSString *)appStoreVersion curVersion:(NSString *)currentVersion {
    NSArray *currentVersionArray = [currentVersion componentsSeparatedByString:@"."];
    NSArray *appStoreVersionArray = [appStoreVersion componentsSeparatedByString:@"."];
    BOOL isReview = NO;
    //比较版本号大小
    int maxv = (int)MAX(currentVersionArray.count, appStoreVersionArray.count);
    int cver = 0;
    int aver = 0;
    for (int i = 0; i < maxv; i++) {
        int aValue = [NSString stringWithFormat:@"%@",appStoreVersionArray[i]].intValue;
        aver = (appStoreVersionArray.count > i) ? aValue : 0;
        
        int cValue = [NSString stringWithFormat:@"%@",currentVersionArray[i]].intValue;
        cver = (currentVersionArray.count > i) ? cValue : 0;
        if(aver != cver) {
            return (aver > cver)? NO : YES;
        }
    }
    return isReview;
}


// 是否在审核
- (void)appStatus:(void (^)(BOOL))completion {
    // 开发环境直接返回NO（不在审核期间）
    if (isProduction) {
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(NO);
        });
        return;
    }
    
    [self requesAppInfoOfAppStoreWithURL:AppStoreUrl_Chine resultBlock:^(NSError *error, NSDictionary *dic) {
        if (error) { completion(NO); return; }
        __block NSDictionary *appStoreDict = dic;
        [self requesAppInfoOfAppStoreWithURL:AppStoreUrl_Other resultBlock:^(NSError *error, NSDictionary *dic) {
            if (error) { completion(NO); return; }
            NSDictionary *newDic = [self analyzeCompareLatestWithChinaData:appStoreDict otherData:dic];
            NSArray *arr = newDic[@"results"];
            MCAppInfoModel *info = [MCAppInfoModel appInfoWithDict:arr.firstObject];
            NSString *appstoreVersion = info.version;
            NSString *curVersion = [self appVersion];
            BOOL isReview = [self isReview:appstoreVersion curVersion:curVersion];
            completion(isReview);
        }];
    }];
}

// 判断刘海屏，返回YES表示是刘海屏
+ (BOOL)isNotchScreen {
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        return NO;
    }
    CGSize size = [UIScreen mainScreen].bounds.size;
    NSInteger notchValue = size.width / size.height * 100;
    if (notchValue == 216 || notchValue == 46) {
        return YES;
    }
    return NO;
}

 
@end

/// 单例的实现
@implementation MCAppVersionManager (Singleton)
static id _instace;
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static MCAppVersionManager *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}
- (id)copyWithZone:(NSZone *)zone { return _instace; }
+ (id)allocWithZone:(struct _NSZone *)zone { return [self sharedInstance]; }
@end

@implementation MCAppInfoModel
+ (instancetype)appInfoWithDict:(NSDictionary *)dict {
    MCAppInfoModel *model = [[MCAppInfoModel alloc] init];
    model.trackId = dict[@"trackId"];
    model.trackName = dict[@"trackName"];
    model.version = dict[@"version"];
    model.bundleId = dict[@"bundleId"];
    model.releaseNotes = dict[@"releaseNotes"];
    model.currentVersionReleaseDate = dict[@"currentVersionReleaseDate"];
    model.trackViewUrl = dict[@"trackViewUrl"];
    return model;
}
@end
